package com.example.fridaykt.service.impl

import com.example.fridaykt.model.*
import com.example.fridaykt.service.SysRoleMenuService
import org.babyfish.jimmer.sql.ast.tuple.Tuple2
import org.babyfish.jimmer.sql.kt.KSqlClient
import org.babyfish.jimmer.sql.kt.ast.expression.eq
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

/**
 *
 */
@Service
@Transactional
class SysRoleMenuServiceImpl(
    private val sqlClient: KSqlClient,
) : SysRoleMenuService {

    override fun updateByRoleIdAndMenuIds(voroleId: Long, menuIds: List<Long>): Boolean {
        val beforeHas = sqlClient.createQuery(SysMenu::class) {
            where(table.sysRoles {
                roleId eq voroleId
            })
            select(table.menuId)
        }.execute()
        val allIds = sqlClient.createQuery(SysMenu::class) {
            select(table.menuId)
        }.execute()
        val set2 = HashSet(menuIds) // 前台返回数据
        val set3 = HashSet(beforeHas) // 数据库中数据
        val delIds = allIds.filter { !set2.contains(it) && set3.contains(it) }
            .map { Tuple2(voroleId, it) }
        val addIds = allIds.filter { set2.contains(it) && !set3.contains(it) }
            .map { Tuple2(voroleId, it) }
        sqlClient.getAssociations(SysRole::sysMenus).deleteAll(delIds)
        sqlClient.getAssociations(SysRole::sysMenus).saveAll(addIds)
        return true
    }
}




